//
//  CZNavigationController.m
//  OCKSFWeibo
//
//  Created by 盛 发 况 on 16/4/18.
//  Copyright © 2016年 盛 发 况. All rights reserved.
//

#import "CZNavigationController.h"
#import "UIBarButtonItem+Item.h"
#import "CZTabBar.h"

@interface CZNavigationController ()<UINavigationControllerDelegate>
@property (nonatomic, strong) id popDelegate;

@end

@implementation CZNavigationController

+ (void)initialize {

    UIBarButtonItem *item = [UIBarButtonItem appearanceWhenContainedIn:self, nil];

    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor orangeColor];
    [item setTitleTextAttributes:attrs forState:UIControlStateNormal];
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.popDelegate = self.interactivePopGestureRecognizer.delegate;
    self.delegate = self;
    
}
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.childViewControllers.count) { // 不是根控制器
        viewController.hidesBottomBarWhenPushed = YES;
        
        UIBarButtonItem *left = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_back"] highImage:[UIImage imageNamed:@"navigationbar_back_highlighted"] target:self action:@selector(popToPre) forControlEvents:UIControlEventTouchUpInside];
        // 设置导航条的按钮
        viewController.navigationItem.leftBarButtonItem = left;
        
        UIBarButtonItem *right = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_more"] highImage:[UIImage imageNamed:@"navigationbar_more_highlighted"] target:self action:@selector(popToRoot) forControlEvents:UIControlEventTouchUpInside];
        viewController.navigationItem.rightBarButtonItem = right;
    }
    [super pushViewController:viewController animated:animated];

}
- (void)popToPre {

    [self popToRootViewControllerAnimated:YES];
}
- (void)popToRoot {

    [self popViewControllerAnimated:YES];
}

#pragma mark -- UINavigationControllerDelegate的代理方法
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {

    UITabBarController *tabBarVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    
    // 删除系统自带的tabBarButton
    for (UIView *tabBarButton in tabBarVc.tabBar.subviews) {
        if ([tabBarButton isKindOfClass:[CZTabBar class]]) {
            [tabBarButton removeFromSuperview];
        }
    }

}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {

    if (viewController == self.childViewControllers[0]) { // 是根控制器
        self.interactivePopGestureRecognizer.delegate = nil;
    } else { // 非根控制器
        self.interactivePopGestureRecognizer.delegate = self.popDelegate;
    }

}

@end





